package com.ms.oschina.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.ms.oschina.api.remote.OkHttpClientManager;
import com.ms.oschina.api.remote.OkHttpClientManager.OnGetNetResultListener;
import com.ms.oschina.api.remote.OsChinaApi;
import com.ms.oschina.base.BaseAsyncTask;
import com.ms.oschina.bean.Constants;
import com.ms.oschina.bean.HttpResponse;
import com.ms.oschina.bean.LoginUserBean;
import com.ms.oschina.bean.Result;
import com.ms.oschina.util.XmlUtils;

public class LoginTask extends BaseAsyncTask<LoginUserBean> {
	private int requestCode;
	private String path;
	private OnGetNetResultListener<LoginUserBean> listener;
	private String user;
	private String password;

	public LoginTask(String path, int requestCode, String user,
			String password, OnGetNetResultListener<LoginUserBean> listener) {
		this.path = path;
		this.requestCode = requestCode;
		this.user = user;
		this.password = password;
		this.listener = listener;
	}

	@Override
	protected LoginUserBean exeCute() throws Exception {
		// 请求登录
		Response response = requestLogin();

		String xmlString = response.body().string();

		LoginUserBean loginUser = XmlUtils.toBean(LoginUserBean.class,
				xmlString.getBytes());
		String errorMessage = loginUser.getResult().getErrorMessage();
		setObject(errorMessage);
		Result result = loginUser.getResult();
		int errorCode = result.getErrorCode();
		setErrorCode(errorCode);// 封装错误码
		if (result.OK()) {// 登录成功
			saveCookie(response);
			// int id = LoginUserBean.getUser().getId();
			// 发送数据 发送cookie 和id
			// loginUser = OsChinaApi.loginUser(id);
		}

		return loginUser;
	}

	public String saveCookie(Response response) {
		// 得到cookie 并保存cookie
		String strCookie = getCookieCid(response);

		List<Cookie> arg1 = new ArrayList<Cookie>();
		Cookie cookie = new Cookie.Builder().name(Constants.Login_Cookie)
				.httpOnly().value(strCookie)
				.domain(response.request().url().host()).build();
		arg1.add(cookie);
		// 持久化存储
		OkHttpClientManager.getInstance().getCookieJar()
				.saveFromResponse(response.request().url(), arg1);
		return strCookie;
	}

	private String getCookieCid(Response response) {
		String header = response.header("set-Cookie");
		int start = header.indexOf("=");
		int end = header.indexOf(";");
		String cookie = header.substring(start + 1, end);
		return cookie;
	}

	private Response requestLogin() throws IOException {
		String content = String.format(OsChinaApi.URL_LOGIN_Cookie, user,
				password);
		// post 提交数据
		RequestBody body = RequestBody
				.create(OkHttpClientManager.Form, content);
		Response response = OkHttpClientManager.getInstance().postSync(path,
				body);
		return response;
	}

	@Override
	protected void onPostExe(HttpResponse<LoginUserBean> result) {
		listener.onGetNetResult(requestCode, result);
	}
}